﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using T163.Open.Api.WP7.Sample.Utility;
using Microsoft.Phone.Tasks;
using T163.Open.Api.WP7.Model;

namespace T163.Open.Api.WP7.Sample
{
    public partial class AuthorizePage : PhoneApplicationPage
    {
        private Consumer consumer;
        private OAuthService oauthservice;

        public AuthorizePage()
        {
            InitializeComponent();

            consumer = new Consumer("B98jYjv5GAhhTm4e", "V4V5r84sy25VPB0pDLdFW8qOFrp6345Q");
        }

        private void btnAcquire_Click(object sender, RoutedEventArgs e)
        {
            oauthservice = new OAuthService();

            oauthservice.GetRequestToken(this.consumer, (p) =>
            {
                WebBrowserTask task = new WebBrowserTask();
                task.Uri = new Uri(p);
                task.Show();
            });
        }

        private void btnConfirmPIN_Click(object sender, RoutedEventArgs e)
        {
            string verifier = txtPIN.Text;

            oauthservice.GetAccessToken(verifier, token =>
                {
                    IsoStoreHelper.Add(App.ACCESSTOKEN, token);
                    IsoStoreHelper.Add(App.CONSUMERTOKEN, this.consumer);

                    oauthservice.VerifyCredentials(user =>
                        {
                            App.User = user;
                            IsoStoreHelper.Add(App.LOGONUSER, user);

                            Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
                            });
                        }, null);                   
                }, null);
        }        
    }
}